package com.wswy.wyjk.ui.practiceNew;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.github.iielse.switchbutton.SwitchView;
import com.my.httpapi.api.annotation.ViewL;
import com.my.httpapi.api.baseUtils.Toast;
import com.my.httpapi.api.baseView.BaseActivity;
import com.tencent.mmkv.MMKV;
import com.wswy.wyjk.R;
import com.wswy.wyjk.api.Api;
import com.wswy.wyjk.api.MMKVConstant;
import com.wswy.wyjk.api.entity.RequestParameter;
import com.wswy.wyjk.ui.login.LoginActivity;
import com.wswy.wyjk.ui.main.event.RankEvent;
import com.wswy.wyjk.ui.main.event.RankFinishEvent;
import com.wswy.wyjk.ui.main.model.ErrResponse;
import com.wswy.wyjk.ui.practiceNew.Dialog.CustomDialog;
import com.wswy.wyjk.ui.practiceNew.event.UpdateErrCountEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ViewL(R.layout.activity_err_topic)
public class ErrTopicActivity extends BaseActivity {

    private TextView tvTodayErr, tvAllErr, tvErrChoose1, tvErrChoose3, tvErrCount, tvErrName;
    private SwitchView switchView;
    private View rlErrChoose;

    private MMKV mmkv;
    private String totalStr, todayStr;
    private String typeName;
    private String token;

    @Override
    protected void initData(Bundle savedInstanceState) {
        initView();
        initData();
    }

    @Override
    protected String showTitle() {
        typeName = getIntent().getStringExtra("type");
        return typeName + "本";
    }

    @Override
    protected boolean statusBarIsBlack() {
        return true;
    }

    @Override
    public void titleRightOnclick() {
        super.titleRightOnclick();
        new CustomDialog.Builder(ErrTopicActivity.this).setTitle("是否确定清空题库，清空后无法还原")
                .setPositiveButton("是", (dialog, which) -> {
                    if (typeName.equals("错题")) {
                        clearErr();
                    } else {
                        clearCollect();
                    }
                }).setNegativeButton("否", (dialog, which) -> {
        }).create().show();
    }



    @Override
    protected void destroy() {
        EventBus.getDefault().unregister(this);
    }

    private void initView() {
        isShowTitleLeft(View.VISIBLE);
        setTitleIconRight(R.drawable.err_delete);
        tvTodayErr = findViewById(R.id.tv_today_err);
        tvAllErr = findViewById(R.id.tv_all_err);
        tvErrChoose1 = findViewById(R.id.tv_err_choose_1);
        tvErrChoose3 = findViewById(R.id.tv_err_choose_3);
        switchView = findViewById(R.id.err_switch);
        tvErrCount = findViewById(R.id.tv_err_count);
        tvErrName = findViewById(R.id.tv_err_name);
        rlErrChoose = findViewById(R.id.rl_err_choose);
    }

    private void initData() {
        EventBus.getDefault().register(this);
        mmkv = MMKV.defaultMMKV();
        token = mmkv.decodeString(MMKVConstant.TOKEN);
        tvErrName.setText(typeName + "数");
        tvAllErr.setText("全部" + typeName);
        if ("收藏".equals(typeName)) {
            rlErrChoose.setVisibility(View.GONE);
        }
        int errCount = mmkv.decodeInt(MMKVConstant.ERRCOUNT, 1);
        choose1or3(errCount);
        tvTodayErr.setOnClickListener(view -> {
            Map<String, Object> map = new HashMap<>();
            map.put("type", 7);
            map.put("sql", todayStr);
            map.put("typeName",typeName);
            intent(PracticeNewActivity.class, map);
        });
        tvAllErr.setOnClickListener(view -> {
            Map<String, Object> map = new HashMap<>();
            map.put("type", 7);
            map.put("sql", totalStr);
            map.put("typeName",typeName);
            intent(PracticeNewActivity.class, map);
        });
        tvErrChoose1.setOnClickListener(view -> choose1or3(1));
        tvErrChoose3.setOnClickListener(view -> choose1or3(3));
        switchView.setOpened(errCount == 0 ? false : true);
        switchView.setOnClickListener(v -> {
            boolean isOpened = switchView.isOpened();
            if (isOpened) {
                tvErrChoose1.setVisibility(View.VISIBLE);
                tvErrChoose3.setVisibility(View.VISIBLE);
                choose1or3(1);
            } else {
                tvErrChoose1.setVisibility(View.GONE);
                tvErrChoose3.setVisibility(View.GONE);
                mmkv.encode(MMKVConstant.ERRCOUNT, 0);
            }
        });
        if (TextUtils.isEmpty(token)) {
            intent(LoginActivity.class);
            return;
        }
        if (typeName.equals("错题")) {
            getErrTopic();
        } else {
            getCollect();
        }
    }

    private void choose1or3(int errCount) {
        if (errCount == 1) {
            tvErrChoose1.setCompoundDrawablesWithIntrinsicBounds(R.drawable.err_single, 0, 0, 0);
            tvErrChoose3.setCompoundDrawablesWithIntrinsicBounds(R.drawable.err_single_nor, 0, 0, 0);
        } else if (errCount == 3) {
            tvErrChoose1.setCompoundDrawablesWithIntrinsicBounds(R.drawable.err_single_nor, 0, 0, 0);
            tvErrChoose3.setCompoundDrawablesWithIntrinsicBounds(R.drawable.err_single, 0, 0, 0);
        } else {
            tvErrChoose1.setVisibility(View.GONE);
            tvErrChoose3.setVisibility(View.GONE);
        }
        mmkv.encode(MMKVConstant.ERRCOUNT, errCount);
    }

    private void clearErr() {
        subscribe(Api.getApi().answerEmpty(RequestParameter.generate().getSingedParams()),
                request(data -> {
                    Toast.show("清除成功");
                    getErrTopic();
                }, true));
    }

    private void clearCollect() {
        subscribe(Api.getApi().favoritesEmpty(RequestParameter.generate().getSingedParams()),
                request(data -> {
                    Toast.show("清除成功");
                    getCollect();
                }, true));
    }

    private void getErrTopic() {
        totalStr = "( ";
        todayStr = "( ";
        subscribe(Api.getApi().answerList(RequestParameter.generate().getSingedParams()),
                request(data -> {
                    getData((ErrResponse) data);
                }, true));
    }

    private void getCollect() {
        totalStr = "( ";
        todayStr = "( ";
        subscribe(Api.getApi().favoritesList(RequestParameter.generate().getSingedParams()),
                request(data -> {
                    getData((ErrResponse) data);
                }, true));
    }

    private void getData(ErrResponse errResponse) {
        int todayCount = errResponse.getToday().getNum();
        int totalCount = errResponse.getTotal().getNum();
        tvErrCount.setText(totalCount + "");
        tvTodayErr.setText("今日" + typeName + "(" + todayCount + ")");
        getTotalStr(errResponse.getTotal().getList());
        getToadyStr(errResponse.getToday().getList());
    }

    private void getTotalStr(List<String> totalList) {
        for (int i = 0; i < totalList.size(); i++) {
            if (i == totalList.size() - 1) {
                totalStr += totalList.get(i);
            } else {
                totalStr += totalList.get(i) + ",";
            }
        }
        totalStr += " )";
    }

    private void getToadyStr(List<String> totalList) {
        for (int i = 0; i < totalList.size(); i++) {
            if (i == totalList.size() - 1) {
                todayStr += totalList.get(i);
            } else {
                todayStr += totalList.get(i) + ",";
            }
        }
        todayStr += " )";
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateErrCount(UpdateErrCountEvent updateErrCountEvent) {
        if (typeName.equals("错题")) {
            getErrTopic();
        } else {
            getCollect();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void finishEvent(RankFinishEvent rankFinishEvent) {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void rankEvent(RankEvent rankEvent) {
        token = mmkv.decodeString(MMKVConstant.TOKEN);
        if (typeName.equals("错题")) {
            getErrTopic();
        } else {
            getCollect();
        }
    }
}
